﻿

using Data.Model.SQLite;

using DataService;
using DataService.Core.Common;
using DataService.Core.DataHelper;
using DataService.Core.ServiceDTO;
using DataService.Data;
using DataService.Main;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SQLite;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

using PersonnelInfo = Data.Model.SQLite.PersonnelInfo;

namespace UnitTest
{
    public class TestSqllite
    {
        public void TestProvider()
        {
            //  SQLiteConnection sQLiteConnection = new SQLiteConnection();
            // System.Data.SQLite.SQLiteFactory factory = new System.Data.SQLite.SQLiteFactory();
            for (int i = 0; i < 10; i++)
            {
                var db = DBMangerFactory.CreateProvider(DatabaseType.SQLite);
                db.ConnectionString = @"D:\Test_SqliteDB\SqliteDB\202205\111.db";
                var d = db.ProviderFactory;
                //var c = db.DbConnection;
                Console.WriteLine($"sqliteDB：" + db.GetHashCode());
            }
        }

        public void TestSqliteConn()
        {
            string connectionString = string.Format("Data Source={0};", @"D:\Test_1.db");
            DbConnection dbConnection = new SQLiteConnection(connectionString);
            dbConnection.Open();

            DbConnection dbConnection1 = new SQLiteConnection(connectionString);
            dbConnection1.Open();

            DbConnection dbConnection2 = new SQLiteConnection(connectionString);
            dbConnection2.Open();

            Console.WriteLine(dbConnection.GetHashCode() + "***" + dbConnection1.GetHashCode() + "**" + dbConnection2.GetHashCode());

        }


        private string ConnStr = string.Empty;
        public void CreateTableBase()
        {


            using (var sqlitedb = DataService.DBMangerFactory.CreateProvider(DatabaseType.SQLite))
            {
                string path = DAL.GetModelPath();
                string connectionString = string.Format("Data Source={0};", path);
                sqlitedb.ConnectionString = connectionString;

                var tableNames = ModelDAL.FindAllModeTableNames(sqlitedb);
                string tempDataBaseFilePath = @"D:\DataBaseBack";
                string dataBaseName = "Test_CCC";

                using (var sqldb = DataService.DBMangerFactory.CreateProvider(DatabaseType.SqlServer))
                {
                    sqldb.ConnectionString = ConnStr;

                    ModelDAL.CreateDataBaseSchema(tempDataBaseFilePath, dataBaseName, sqldb);
                }
                List<string> newConns = new List<string>();
                var tempArray = ConnStr.Split(';');
                foreach (var item in tempArray)
                {
                    if (item.Split('=')[0].ToLower() == "database")
                    {
                        newConns.Add($"Database={dataBaseName}");
                    }
                    else
                    {
                        newConns.Add(item);
                    }
                }
                string newConnStr = string.Join(";", newConns);
                using (var sqldb = DataService.DBMangerFactory.CreateProvider(DatabaseType.SqlServer))
                {
                    sqldb.ConnectionString = newConnStr;

                    foreach (var itemTableName in tableNames)
                    {
                        ModelDAL.CreatTableSchema(itemTableName, sqldb);
                    }
                }

            }





        }

        public void TestFromSqlite()
        {
            using (var db = DataService.DBMangerFactory.CreateProvider(DatabaseType.SQLite))
            {
                string connectionString = string.Format("Data Source={0};", @"D:\Test_1.db");
                db.ConnectionString = connectionString;

                ModelDAL.CreateModelCodes(@"D:\UnitTest\Model\", db, "PersonnelInfo_202302");

            }
            Console.WriteLine("完成");
        }

        public void Insert_1()
        {
            Snowflake snowflake1 = new Snowflake();
            using (var db = DataService.DBMangerFactory.CreateProvider(DatabaseType.SQLite))
            {
                string connectionString = string.Format("Data Source={0};", @"D:\Test_1.db");
                db.ConnectionString = connectionString;

                db.IsEnable = true;
                PersonnelInfo_202302 testModel = new PersonnelInfo_202302();
                testModel.ID = snowflake1.NewId();
                testModel.PersonnelName = "分表分库插入，再次雪花插入";
                testModel.AuditState = 18;
                testModel.Sex = true;
                testModel.WorkYear=(decimal)12.6;


                testModel.PersonnelName = "测试姓名";
                testModel.PersonnelNo = "id-001";
                testModel.Status = 1;
                testModel.FullTimeMajor = "测试全日制";
                testModel.PartTimeMajor = "测试非全日制";
                testModel.IDNo = "123456789";
                testModel.Sex = true;
                testModel.TermOfValidity = DateTime.Now.ToShortDateString();
                testModel.LearningWay = "全日制";
                testModel.DepartmentId = Guid.NewGuid().ToString();


                db.TableSuffix = "";
                DAL.Insert<PersonnelInfo_202302>(testModel, db);
              
            }
            Console.WriteLine("完成");
        }


        #region 测试千万级数据

        public void TestCreateTable()
        {
            string tableName = "PersonnelInfo";
            using (var db = DataService.DBMangerFactory.CreateProvider(DatabaseType.SQLite))
            {

                string connectionString = string.Format("Data Source={0};", @"D:\TestBigData.db");
                db.ConnectionString = connectionString;

                db.TableSuffix = "";
                ModelDAL.CreatTableSchema(tableName,db);
                Console.WriteLine($"已完成：{tableName}");
                db.Commit();
            }
            Console.WriteLine("业务表创建完成");

        }

        /// <summary>
        /// 向指定数据库创建表结构
        /// </summary>
        public void TestCreateALLTable()
        {
            //取出所有模型表
            List<string> modelTables = new List<string>();
            using (var db = DataService.DBMangerFactory.CreateProvider(DatabaseType.SQLite))
            {   
                string connectionString = string.Format("Data Source={0};", @"D:\Model\Model.db");
                db.ConnectionString = connectionString;
                var columns = DAL.Query<ModelColumns>(x => true, db);
                modelTables = columns.Select(x => x.TableName).ToList();
                modelTables = modelTables.Distinct().ToList();
            }

            using (var db = DataService.DBMangerFactory.CreateProvider(DatabaseType.SQLite))
            {

                string connectionString = string.Format("Data Source={0};", @"D:\TestBigData.db");
                db.ConnectionString = connectionString;
                //  DAL.CreateDataBase(@"D:\测试千万级数据", "TestBigData", db);

                db.TableSuffix = "";
                foreach (var itemTableName in modelTables)
                {
                    ModelDAL.CreatTableSchema(itemTableName,db);
                    Console.WriteLine($"已完成：{itemTableName}");
                }
            }
            Console.WriteLine("业务表创建完成");

        }


        public void InsertVIRTUAL()
        {
            using (var db = DataService.DBMangerFactory.CreateProvider(DatabaseType.SQLite))
            {
                string connectionString = string.Format("Data Source={0};", @"D:\TestBigData.db");
                db.ConnectionString = connectionString;
                //db._IsolationLevel = IsolationLevel.ReadUncommitted;
                Stopwatch totalSw = new Stopwatch();
                totalSw = Stopwatch.StartNew();
                Snowflake snowflake1 = new Snowflake();
                for (int n = 0; n < 2; n++)
                {
                    List<message> list = new List<message>();
                    var stopWatch = new Stopwatch();
                    stopWatch.Start();
                    for (int i = 0; i < 5000; i++)
                    {
                        message testModel = new message();
                        testModel.title = $"第{(n + 1)}批次，大数据量测试新框架导入大数据量*" + i;
                        testModel.body = "测试实施";
                        list.Add(testModel);
                    }
                    DAL.BeatchInsert(list, db);
                    Console.WriteLine("插入sqlite耗时" + stopWatch.ElapsedMilliseconds);
                    stopWatch.Stop();
                }

                db.Commit();
                totalSw.Stop();
                Console.WriteLine($"总计耗时：{totalSw.ElapsedMilliseconds}毫秒");
                Console.WriteLine("完成");

            }
        }
        #region 随机姓名
        public List<string> Xing = new List<string>() {"赵", "钱", "孙", "李", "周", "吴", "郑", "王", "冯", "陈", "楮", "卫", "蒋", "沈", "韩", "杨",
        "朱", "秦", "尤", "许", "何", "吕", "施", "张", "孔", "曹", "严", "华", "金", "魏", "陶", "姜",
        "戚", "谢", "邹", "喻", "柏", "水", "窦", "章", "云", "苏", "潘", "葛", "奚", "范", "彭", "郎",
        "鲁", "韦", "昌", "马", "苗", "凤", "花", "方", "俞", "任", "袁", "柳", "酆", "鲍", "史", "唐",
        "费", "廉", "岑", "薛", "雷", "贺", "倪", "汤", "滕", "殷", "罗", "毕", "郝", "邬", "安", "常",
        "乐", "于", "时", "傅", "皮", "卞", "齐", "康", "伍", "余", "元", "卜", "顾", "孟", "平", "黄",
        "和", "穆", "萧", "尹", "姚", "邵", "湛", "汪", "祁", "毛", "禹", "狄", "米", "贝", "明", "臧",
        "计", "伏", "成", "戴", "谈", "宋", "茅", "庞", "熊", "纪", "舒", "屈", "项", "祝", "董", "梁",
        "杜", "阮", "蓝", "闽", "席", "季", "麻", "强", "贾", "路", "娄", "危", "江", "童", "颜", "郭",
        "梅", "盛", "林", "刁", "锺", "徐", "丘", "骆", "高", "夏", "蔡", "田", "樊", "胡", "凌", "霍",
        "虞", "万", "支", "柯", "昝", "管", "卢", "莫", "经", "房", "裘", "缪", "干", "解", "应", "宗",
        "丁", "宣", "贲", "邓", "郁", "单", "杭", "洪", "包", "诸", "左", "石", "崔", "吉", "钮", "龚",
        "程", "嵇", "邢", "滑", "裴", "陆", "荣", "翁", "荀", "羊", "於", "惠", "甄", "麹", "家", "封",
        "芮", "羿", "储", "靳", "汲", "邴", "糜", "松", "井", "段", "富", "巫", "乌", "焦", "巴", "弓",
        "牧", "隗", "山", "谷", "车", "侯", "宓", "蓬", "全", "郗", "班", "仰", "秋", "仲", "伊", "宫",
        "宁", "仇", "栾", "暴", "甘", "斜", "厉", "戎", "祖", "武", "符", "刘", "景", "詹", "束", "龙",
        "叶", "幸", "司", "韶", "郜", "黎", "蓟", "薄", "印", "宿", "白", "怀", "蒲", "邰", "从", "鄂",
        "索", "咸", "籍", "赖", "卓", "蔺", "屠", "蒙", "池", "乔", "阴", "郁", "胥", "能", "苍", "双",
        "闻", "莘", "党", "翟", "谭", "贡", "劳", "逄", "姬", "申", "扶", "堵", "冉", "宰", "郦", "雍",
        "郤", "璩", "桑", "桂", "濮", "牛", "寿", "通", "边", "扈", "燕", "冀", "郏", "浦", "尚", "农",
        "温", "别", "庄", "晏", "柴", "瞿", "阎", "充", "慕", "连", "茹", "习", "宦", "艾", "鱼", "容",
        "向", "古", "易", "慎", "戈", "廖", "庾", "终", "暨", "居", "衡", "步", "都", "耿", "满", "弘",
        "匡", "国", "文", "寇", "广", "禄", "阙", "东", "欧", "殳", "沃", "利", "蔚", "越", "夔", "隆",
        "师", "巩", "厍", "聂", "晁", "勾", "敖", "融", "冷", "訾", "辛", "阚", "那", "简", "饶", "空",
        "曾", "毋", "沙", "乜", "养", "鞠", "须", "丰", "巢", "关", "蒯", "相", "查", "后", "荆", "红",
        "游", "竺", "权", "逑", "盖", "益", "桓", "公", "仉", "督", "晋", "楚", "阎", "法", "汝", "鄢",
        "涂", "钦", "岳", "帅", "缑", "亢", "况", "后", "有", "琴", "归", "海", "墨", "哈", "谯", "笪",
        "年", "爱", "阳", "佟", "商", "牟", "佘", "佴", "伯", "赏",
        "万俟", "司马", "上官", "欧阳", "夏侯", "诸葛", "闻人", "东方", "赫连", "皇甫", "尉迟", "公羊",
        "澹台", "公冶", "宗政", "濮阳", "淳于", "单于", "太叔", "申屠", "公孙", "仲孙", "轩辕", "令狐",
        "锺离", "宇文", "长孙", "慕容", "鲜于", "闾丘", "司徒", "司空", "丌官", "司寇", "子车", "微生",
        "颛孙", "端木", "巫马", "公西", "漆雕", "乐正", "壤驷", "公良", "拓拔", "夹谷", "宰父", "谷梁",
        "段干", "百里", "东郭", "南门", "呼延", "羊舌", "梁丘", "左丘", "东门", "西门", "南宫"};

        string _lastNameMan = "刚伟勇毅俊峰强军平保东文辉力明永健世广志义兴良海山仁波宁贵福生龙元全国胜学祥才发武新利清飞彬富顺信子杰涛昌成康星光天达安岩中茂进林有坚和彪博诚先敬震振壮会思群豪心邦承乐绍功松善厚庆磊民友裕河哲江超浩亮政谦亨奇固之轮翰朗伯宏言若鸣朋斌梁栋维启克伦翔旭鹏泽晨辰士以建家致树炎德行时泰盛雄琛钧冠策腾楠榕风航弘";


        string _lastNameWoMan = "秀娟英华慧巧美娜静淑惠珠翠雅芝玉萍红娥玲芬芳燕彩春菊兰凤洁梅琳素云莲真环雪荣爱妹霞香月莺媛艳瑞凡佳嘉琼勤珍贞莉桂娣叶璧璐娅琦晶妍茜秋珊莎锦黛青倩婷姣婉娴瑾颖露瑶怡婵雁蓓纨仪荷丹蓉眉君琴蕊薇菁梦岚苑婕馨瑗琰韵融园艺咏卿聪澜纯毓悦昭冰爽琬茗羽希宁欣飘育滢馥筠柔竹霭凝鱼晓欢霄枫芸菲寒伊亚宜可姬舒影荔枝思丽墨";

        #endregion
        #region 随机生成专业
        string[] majors = new string[] { "通信与计算机网络技术", "网络工程", "网络经济概论", "建筑学", "国际经济学", "市场营销", "会计学", "水利工程", "经管法", "生物工程" };
        #endregion
        #region 随机电话
        string[] phones = new string[] { "13", "15", "16", "17", "18", "19" };


        #endregion
        public void Test111<T, Result>(Func<T, Result> func)
        { 
           
        }
        public void BeatchInsert()
        {
            using (var db = DataService.DBMangerFactory.CreateProvider(DatabaseType.SQLite))
            {
               
                  string connectionString = string.Format("Data Source={0};Version=3;", @"D:\Test_1.db");
                db.ConnectionString = connectionString;
                //db._IsolationLevel = IsolationLevel.ReadUncommitted;

                Snowflake snowflake1 = new Snowflake();

                int XingLen = Xing.Count;//501个姓
                char[] ManChar = _lastNameMan.ToCharArray();//151的男士名
                char[] WoManChar = _lastNameWoMan.ToCharArray();//151个女士名
                int ManNameLen = ManChar.Length;//151的男士名
                int WoManNameLen = WoManChar.Length;//151个女士名
                int tempNo = 0;

                for (int n = 0; n <1; n++)
                {
                    Guid departmentId = Guid.NewGuid();
                    List<PersonnelInfo> list = new List<PersonnelInfo>();

                    Random random = new Random();
                    int xingRand = random.Next(XingLen);
                    int mingRand = random.Next(ManNameLen);
                    string xm = Xing[xingRand] + ManChar[mingRand];
                    //string xm = "十大科技发达斯洛伐克";
                    for (int i = 0; i <1000; i++)
                    {
                        tempNo = tempNo + 1;
                        string personNo = tempNo.ToString().PadLeft(6, '0');
                        string idNo = "000000000000000000";
                        try
                        {
                            idNo = IDCardNumber.generate();
                        }
                        catch
                        {
                            idNo = "000000000000000000";
                        }
                        Random random1 = new Random();
                        int majorRand = random1.Next(majors.Length);
                        string tempfullMajor = majors[majorRand];
                        majorRand = random1.Next(majors.Length);
                        string partMajor = majors[majorRand];
                        
                        PersonnelInfo testModel = new PersonnelInfo();
                        testModel.ID = snowflake1.NewId(DateTime.Now.AddMonths(-5));
                        testModel.PersonnelName = xm;
                        testModel.PersonnelNo = personNo;
                        testModel.Status = 1;
                        testModel.FullTimeMajor = tempfullMajor;
                        testModel.PartTimeMajor = partMajor;
                        testModel.IDNo = idNo;
                        testModel.Sex = true;
                        testModel.TermOfValidity=DateTime.Now.ToShortDateString();
                        testModel.LearningWay = "全日制";

                        int num = random.Next(10);
                        string tempStr1 = string.Empty;
                        for (int l = 0; l < num; l++)
                        {
                          
                            for (int k = 0; k <7; k++)
                            {
                                int tempRand = random.Next(ManNameLen);
                                tempStr1 = tempStr1 + ManChar[tempRand];
                            }

                        }

                        testModel.FullTimeUniversity = tempStr1;


                        int num1 = random.Next(10);
                        string tempStr2 = string.Empty;
                        for (int l = 0; l < num1; l++)
                        {

                            for (int k = 0; k < 6; k++)
                            {
                                int tempRand = random.Next(ManNameLen);
                                tempStr2 = tempStr2 + ManChar[tempRand];
                            }

                        }
                        testModel.PartTimeUniversity = tempStr2;
                        int d = RandHelper.Next(111111111, 999999999);

                        int pd = random1.Next(phones.Length);
                        string s = phones[pd];
                        s = s + d.ToString();

                        testModel.Phone = s;

                        int dd = random1.Next(100);
                        testModel.FullTimeGraduationTime = DateTime.Now.AddDays(dd).ToString("yyyy-MM-dd");
                        dd = random1.Next(100);
                        testModel.PartTimeGraduationTime = DateTime.Now.AddDays(dd).ToString("yyyy-MM-dd");
                        dd = random1.Next(100);
                        testModel.SocialLastTime = DateTime.Now.AddDays(dd).ToString("yyyy-MM-dd");
                        testModel.EmployeeType = "在职";

                        int dds = random.Next(6);
                        List<string> tempDatas = new List<string>();
                        for (int l = 0; l < dds; l++)
                        {
                            string tempStr = string.Empty;
                            for (int k = 0; k < 5; k++)
                            {
                                int tempRand = random.Next(ManNameLen);
                                tempStr = tempStr + ManChar[tempRand];
                            }
                            tempDatas.Add(tempStr);
                        }

                        testModel.CertificateNames = string.Join(",", tempDatas);
                        testModel.DepartmentId = departmentId.ToString();

                        list.Add(testModel);
                    }

                    DAL.Insert(list, db);
                    db.Commit();
                    Console.WriteLine($"线程：{Thread.CurrentThread.ManagedThreadId}，提交时间：{DateTime.Now}");
                }
               


                Console.WriteLine("完成");

            }

        }
        public void ReadData()
        {

            using (var db = DataService.DBMangerFactory.CreateProvider(DatabaseType.SQLite))
            {
                string connectionString = string.Format("Data Source={0};", @"D:\Test_1.db");
                db.ConnectionString = connectionString;
                int recordCount = 0;
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                //页码，先正向查询，再逆向，再正向
                int[] pageIndexs = new int[] { 1, 2, 6, 8,7,6,5,4,3, 2, 3, 7,1,5 };
                ResultPageDTO resultPageDTO = new ResultPageDTO();
                foreach (var itemIndex in pageIndexs)
                {

                    RequestPageDTO paramDTO = new RequestPageDTO
                    {
                        PageIndex = itemIndex,
                        PageSize = 20,
                        ParamNextStartId = resultPageDTO.ParamNextStartId,
                        ParamUpStartId = resultPageDTO.ParamUpStartId,
                        UniqueKey = resultPageDTO.UniqueKey
                    };
                      db.TableSuffix = "_202303";
                    // var tempArray = DAL.QueryPage<TB_PersonnelInformation>(x =>true&&x.PersonnelName.Contains("第1000批次"),30, 499999, null, null, out recordCount, db,t=>new {t.ID,t.PersonnelNo,t.PersonnelName });

                    //&& x.PersonnelName== "劳光"
                    string[] ffff = new string[] { "测试1", "测试2", "测试3" };
                    //x => true&& x.DepartmentId!= ""&&x.PersonnelNo=="ddd"&&x.PersonnelName=="aaa"&&x.IsDelete
                    var tempArray = DAL.QueryPage<Data.Model.SQLite.PersonnelInfo>(x =>x.PersonnelName== "管信", paramDTO, db, ref resultPageDTO, t => new { t.ID, t.PersonnelNo });
                    Console.WriteLine($"第{itemIndex}页返回的唯一标识：{resultPageDTO.UniqueKey}，最大Id：{resultPageDTO.ParamNextStartId},最小Id{resultPageDTO.ParamUpStartId}");
                    Console.WriteLine($"****************************第{itemIndex}页*******************************");
                    var tempList = tempArray.ToList();
                    foreach (var item in tempList)
                    {
                        Console.WriteLine(item.ID + "**" + item.PersonnelName + "***" + item.PersonnelNo + "**" + item.AuditState);
                    }
                    Console.WriteLine($"****************************第{itemIndex}页*******************************");
                    recordCount = resultPageDTO.TotalCount;
                }
                stopwatch.Stop();
                Console.WriteLine($"读取数据流耗时：{stopwatch.ElapsedMilliseconds}；总行数：{recordCount}");
                stopwatch.Restart();

                stopwatch.Stop();



                Console.WriteLine("完成");


            }

        }
        #endregion


        public void TestSqliteSchema()
        {


            using (var db = DataService.DBMangerFactory.CreateProvider(DatabaseType.SQLite))
            {
                string connectionString = string.Format("Data Source={0};", @"D:\Test_1.db");
                // string connectionString = "连接字符串";
                db.ConnectionString = connectionString;

                //  DataTable dataTable = db.DbConnection.GetSchema("Tables", new string[] { null, null, null, "TABLE" });
                DataTable dataTable = db.DbConnection.GetSchema("Tables");
                DataTable dataTable11 = db.DbConnection.GetSchema();

                //1.获取表名
                //foreach (System.Data.DataRow itemRow in dataTable.Rows)
                //{
                //    Console.WriteLine(itemRow["TABLE_NAME"]);
                //}
                //2.获取列

                ////DataTable columnData = db.DbConnection.GetSchema("Columns", new string[] { null, null, "BackUpFileData" });
                //DataTable columnData = db.DbConnection.GetSchema(typeof(ModelColumns).Name, new string[] { null, null, "BackUpFileData" });

                //List<ModelColumns> list = new List<ModelColumns>();

                //for (int i = 0; i < columnData.Rows.Count; i++)
                //{
                //    string aa = "";
                //    for (int j = 0; j < columnData.Columns.Count; j++)
                //    {
                //        aa += "\n" + columnData.Columns[j].ColumnName + "：" + columnData.Rows[i][j].ToString();
                //    }
                //    // Console.WriteLine(aa);
                //    var itemRow = columnData.Rows[i];
                //    ModelColumns columns = new ModelColumns();
                //    columns.TableName = itemRow["TABLE_NAME"].ToString();
                //    int.TryParse(itemRow["ORDINAL_POSITION"].ToString(), out int colOrder);
                //    columns.ColOrder = colOrder;
                //    columns.ColName = itemRow["COLUMN_NAME"].ToString();
                //    columns.ColType = itemRow["DATA_TYPE"].ToString();
                //    int.TryParse(itemRow["CHARACTER_OCTET_LENGTH"].ToString(), out int colLength);
                //    columns.ColLength = colLength;

                //    int.TryParse(itemRow["CHARACTER_MAXIMUM_LENGTH"].ToString(), out int valueLength);
                //    columns.ValueLength = valueLength;
                //    int.TryParse(itemRow["NUMERIC_SCALE"].ToString(), out int scaleLength);
                //    columns.ScaleLength = scaleLength;

                //    columns.IsNullable = itemRow["IS_NULLABLE"].ToString() == "YES" ? true : false;

                //    columns.DefaultValue = itemRow["COLUMN_DEFAULT"].ToString();

                //    //columns. FieldDes

                //    list.Add(columns);
                //}

               List<ModelIndexs> indexsList = new List<ModelIndexs>();
                // DataTable indexesData = db.DbConnection.GetSchema(typeof(ModelIndexs).Name);

                var ddd = db.DbConnection.GetSchema("Indexes");

                var bbb = db.DbConnection.GetSchema("Indexes", new string[] { null, null, "PersonnelInfo_202302" });

                DataTable indexesColumnData = db.DbConnection.GetSchema("IndexColumns");

                for (int i = 0; i < indexesColumnData.Rows.Count; i++)
                {
                    string aa = "";
                    for (int j = 0; j < indexesColumnData.Columns.Count; j++)
                    {
                        aa += "\n" + indexesColumnData.Columns[j].ColumnName + "：" + indexesColumnData.Rows[i][j].ToString();
                    }
                    Console.WriteLine(aa);

                    string tableName = indexesColumnData.Rows[i]["TABLE_NAME"].ToString();
                    string index_NAME = indexesColumnData.Rows[i]["INDEX_NAME"].ToString();
                    string column_NAME = indexesColumnData.Rows[i]["COLUMN_NAME"].ToString();
                    string sort = indexesColumnData.Rows[i]["SORT_MODE"].ToString();

                    indexsList.Add(new ModelIndexs
                    {
                        TableName = tableName,
                        IndexName = index_NAME,
                        ColumnName = column_NAME,
                        Sort = sort
                    });

                }
                Console.WriteLine("*******************************************************");
                //for (int i = 0; i < indexesData.Rows.Count; i++)
                //{
                //    string aa = "";
                //    for (int j = 0; j < indexesData.Columns.Count; j++)
                //    {
                //        aa += "\n" + indexesData.Columns[j].ColumnName + "：" + indexesData.Rows[i][j].ToString();
                //    }
                //    Console.WriteLine(aa);
                //    string tableName = indexesData.Rows[i]["TABLE_NAME"].ToString();
                //    string indexName = indexesData.Rows[i]["INDEX_NAME"].ToString();
                //    var tempIndexModel = indexsList.Find(x => x.TableName == tableName && x.IndexName == indexName);
                //    if (tempIndexModel != null)
                //    {
                //        bool ispk = Convert.ToBoolean(indexesData.Rows[i]["PRIMARY_KEY"].ToString());
                //        bool isUNIQUE = Convert.ToBoolean(indexesData.Rows[i]["UNIQUE"].ToString());
                //        tempIndexModel.PrimaryKey = ispk;
                //        tempIndexModel.UQIQUE = isUNIQUE;
                //    }
                //}

               // DataTable foreignKeysData = db.DbConnection.GetSchema("ForeignKeys");


            }

        }
    }



    public class IDCardNumber
    {

        //生成随机年份
        public static int generateYear()
        {
            StringBuilder bu = new StringBuilder();
            Random rd = new Random();
            int year = rd.Next(1900, DateTime.Now.Year);
            bu.Append(year);
            return int.Parse(bu.ToString());
        }
        //生成
        public static string generate()
        {
            StringBuilder bu = new StringBuilder();
            Random rd = new Random();
            bu.Append(110000);
            int year = generateYear();
            bu.Append(year);
            int month = rd.Next(1, 12);
            if (month < 10)
            {
                bu.Append(0);
            }
            bu.Append(month);
            int[] days;
            if (isleapyear(year))
            {
                days = new int[12] { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
            }
            else
            {
                days = new int[12] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
            }

            int day = rd.Next(1, days[month]);
            if (day < 10)
            {
                bu.Append(0);
            }
            bu.Append(day);
            bu.Append(randomcode());
            int[] c = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
            char[] r = { '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2' };
            string convert = bu.ToString();

            int it = 0;
            int res = 0;
            //  Console.WriteLine(res);

            while (it < 17)
            {
                res = res + (convert[it] - '0') * c[it];
                //   Console.WriteLine("第"+it+"次,"+convert[it]+"乘以"+c[it]);
                //    Console.WriteLine(res);
                it++;
            }


            int i = res % 11;
            bu.Append(r[i]);
            return bu.ToString();
        }
        //生成3位随机
        public static string randomcode()
        {
            StringBuilder bu = new StringBuilder();
            Random rd = new Random();
            int code = rd.Next(1, 999);
            if (code < 10)
            {
                bu.Append(00);
            }
            else if (code < 100)
            {
                bu.Append(0);
            }
            bu.Append(code);
            return bu.ToString();
        }


        public static bool isleapyear(int year)
        {
            if (year % 4 == 0)
            {
                if (year % 100 == 0 && year % 400 != 0)
                {
                    return false;
                }
                return true;
            }
            return false;
        }




    }
}
